package question.solution2;

import question.SolutionTemplate;

public class Solution2 implements SolutionTemplate {

    class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode();
        ListNode p1 = l1;
        ListNode p2 = l2;
        boolean carry = false;
        ListNode lastNode = null;
        while(p1 != null || p2 != null){
            int p1Value = 0;
            int p2Value = 0;
            if(p1 != null){
                p1Value = p1.val;
            }
            if(p2 != null){
                p2Value = p2.val;
            }
            int pSum = p1Value + p2Value + (carry ? 1:0);
            int currentPosition = pSum % 10;
            ListNode currentNode = new ListNode(currentPosition);
            if(lastNode != null){
                lastNode.next = currentNode;
            }else{
                result = currentNode;
            }
            lastNode = currentNode;
            if(p1 != null){
                p1 = p1.next;
            }
            if(p2 != null){
                p2 = p2.next;
            }
            carry = pSum / 10 == 0 ? false : true;
        }
        if(carry){
            ListNode currentNode = new ListNode(1);
            lastNode.next = currentNode;
        }

        return result;
    }

    @Override
    public void test() {

    }

}
